package repository

import (
	"context"
	"fmt"
	"time"
)

type WallpaperMeta struct {
	ID           int64     `json:"id"`
	Name         string    `json:"name"`
	PreviewURL   string    `json:"preview_url"`
	VIPType      int64     `json:"vip_type"`
	Hot          int64     `json:"hot"`
	AuthorUID    int64     `json:"author_uid"`
	WpType       int64     `json:"wp_type"`
	WpURL        string    `json:"wp_url"`
	PreviewVideo string    `json:"preview_video"`
	OriginVideo  string    `json:"origin_video"`
	AssetID      int64     `json:"asset_id"`
	ExtraParam   string    `json:"extra_param"`
	CreateTime   time.Time `json:"create_time"`
	UpdateTime   time.Time `json:"update_time"`
}

type WallpaperMetaStore struct {
}

func (m *WallpaperMetaStore) tableName() string {
	return "wallpaper_meta"
}

func (m *WallpaperMetaStore) Create(ctx context.Context, meta *WallpaperMeta) error {
	sqlTmp := "INSERT INTO %v(name, preview_url, vip_type, hot, author_uid, wp_type, wp_url, preview_video, origin_video, asset_id, extra_param) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
	sql := fmt.Sprintf(sqlTmp, m.tableName())
	return db.Exec(sql, meta.Name, meta.PreviewURL, meta.VIPType, meta.Hot, meta.AuthorUID, meta.WpType, meta.WpURL, meta.PreviewVideo, meta.OriginVideo, meta.AssetID, meta.ExtraParam).Error
}

func (m *WallpaperMetaStore) ListByType(ctx context.Context, wpType int64) ([]*WallpaperMeta, error) {
	sqlTmp := "SELECT * FROM %v WHERE wp_type = ? ORDER BY create_time" // TODO order by hot
	sql := fmt.Sprintf(sqlTmp, m.tableName())

	var metas []*WallpaperMeta
	err := db.Raw(sql, wpType).Scan(&metas).Error
	if err != nil {
		return nil, err
	}
	return metas, nil
}
